#!/bin/bash
function init() {
    LOCALE=(LANG LC_COLLATE LC_CTYPE LC_MESSAGES LC_MONETARY LC_NUMERIC LC_TIME LC_ALL)
    LANGUAGE="zh_CN.UTF-8"
    for l in "${LOCALE[@]}" ; do
        export "$l=$LANGUAGE"
    done
    TYPE=(":sparkles: feat" ":bug: fix" ":memo: docs" ":art: style" ":hammer: refactor" ":white_check_mark: test" ":wrench: chore" ":zap: perf")
}

# 验证当前是否为Git项目
function verify {
    git rev-parse --show-toplevel > /dev/null 2>&1
    GIT_VERIFY=$?
    if test $GIT_VERIFY != 0; then
      >&2 echo "fatal: Not a git repository (or any of the parent directories): .git"
      exit $GIT_VERIFY
    fi
}
# 消息主体
function mainMessage() {
    echo "选择您正在提交的类型:
        1. feat: 新功能（ Introducing new features ）
        2. fix: 修补bug ( Fixing a bug )
        3. docs: 文档（ Writing docs ）
        4. style: 格式（ Improving structure / format of the code ）
        5. refactor: 重构（ Refactoring code ）
        6. test: 增加测试 ( Adding tests )
        7. chore: 构建过程或辅助工具的变动 ( Changing configuration files. )
        8. perf:  改善性能 ( Improving performance )
        0. quit: 退出 ( Exit )
    "
    read -e -n 1 -p "请选择相关数字选项 [0-8]> "

    if [[ $REPLY =~ ^[0-8]$ ]]; then
        if [[ $REPLY == 0 ]]; then
            echo "退出本次提交"
            exit
        fi
        type=${TYPE[$REPLY-1]}
    else
        echo "无效的输入" >&2
        exit 1
    fi

    echo '本次提交的范围，建议填写版本号 ($version):'
    read -e scope
    echo
    echo "请添加简短的，必要的对本次提交的描述:"
    read -e subject
    echo
    echo "添加一个完整提交的描述:"
    IFS=''
    read -e body
    while :
        do
           read -e bodyLine
           if [ "$bodyLine" == "" ]; then
                break           #终止循环.
           fi
           body="$body\n$bodyLine"
        done
    body="$(echo -e $body)"

    echo "列出本次提交解决的、可以关闭的所有相关问题，建议使用关键字 refs 、 close:"
    IFS=' '
    read -e footer
    while :
        do
           read -e footerLine
           if [ "$footerLine" == "" ]; then
                break           #终止循环.
           fi
           footer="$footer\n$footerLine"
        done
    footer="$(echo -e $footer)"
    echo
}
# 其他消息内容
function otherMessage() {
    #add Signed off by
    SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
}
# 构建消息
function build() {
    if [ -z "$*" ]; then
        ALL="-a"
    else
        ALL=$*
    fi
    MSGFILE="`git rev-parse --git-dir`COMMIT-MSG.tmp"

    echo "$type($scope): $subject" > $MSGFILE
    echo "" >> $MSGFILE
    echo "$body" >> $MSGFILE
    echo "" >> $MSGFILE
    echo "$footer" >> $MSGFILE
    echo "" >> $MSGFILE
    echo "$SOB" >> $MSGFILE

}
# 执行提交
function run() {
    GIT_COMMIT_CMD="git commit -F $MSGFILE $ALL"
    echo $GIT_COMMIT_CMD
    eval $GIT_COMMIT_CMD
}
# 清除临时文件
function clean() {
    rm -f $MSGFILE
}
case $1 in
    *)
        init
        verify
        mainMessage
        otherMessage
        build "$@"
        run
        clean

        ;;
esac